package com.nuanshui.heatedloan.controller.display.credit;

import com.alibaba.dubbo.config.annotation.Reference;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.heatedloan.baseservice.facade.AdvertisementService;
import com.nuanshui.heatedloan.baseservice.facade.ImageService;
import com.nuanshui.heatedloan.constant.FeatureType;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.controller.BaseController;
import com.nuanshui.heatedloan.credit.constant.*;
import com.nuanshui.heatedloan.credit.facade.*;
import com.nuanshui.heatedloan.credit.vo.CustomerCreditResultVO;
import com.nuanshui.heatedloan.credit.vo.CustomerHomePageInfoVO;
import com.nuanshui.heatedloan.credit.vo.PayOrderInfoVO;
import com.nuanshui.heatedloan.dal.vo.AdvertisementVO;
import com.nuanshui.heatedloan.userinfo.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zss
 * @date 2017/7/10 21:20
 * @description
 * @Since
 */
@RequestMapping("credit/homePage")
@RestController
public class CustomerHomePageController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(CustomerHomePageController.class);

    @Reference(url = GlobalParam.CREDIT_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.CREDIT_DUBBO_SERVER_VERSION)
    private CustomerHomePageInfoService customerHomePageInfoService;

    @Reference(url = GlobalParam.BASESERVICE_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.BASESERVICE_DUBBO_SERVER_VERSION)
    private AdvertisementService advertisementService;

    @Reference(url = GlobalParam.BASESERVICE_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.BASESERVICE_DUBBO_SERVER_VERSION)
    private ImageService imageService;

    @Reference(url = GlobalParam.CREDIT_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.CREDIT_DUBBO_SERVER_VERSION)
    private PayOrderInfoService payOrderInfoService;

    @Reference(url = GlobalParam.CREDIT_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.CREDIT_DUBBO_SERVER_VERSION)
    private CustomerCreditResultService customerCreditResultService;

    @Reference(url = GlobalParam.CREDIT_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.CREDIT_DUBBO_SERVER_VERSION)
    private CustomerProduceService customerProduceService;

    @Reference(url = GlobalParam.CREDIT_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.CREDIT_DUBBO_SERVER_VERSION)
    private CreditConvertService creditConvertService;

    @RequestMapping(value = "/loadHome",method = RequestMethod.POST)
    public String loadHome() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("banners", this.getBannerList());
        User user = getCurrentUserNotCheckEmptyId();
        List<CustomerHomePageInfoVO> list = new ArrayList<CustomerHomePageInfoVO>();
        if (user != null && SysStringUtils.isNotEmpty(user.getId())) {//用户登录
            Integer customerStatus = customerHomePageInfoService.getCustomerStatus(user.getId());
            logger.info("-----当前用户状态customerStatus=" + customerStatus);
            resultMap.put("userStatus", customerStatus);
            switch (customerStatus) {
                case UserStatusType.NOT_COMPUTE_AMOUNT://未计算额度，产品显示模板数据
                    list = customerHomePageInfoService.getDefaultList();
                    resultMap.put("products", list);
                    break;
                case UserStatusType.COMPUTING_AMOUNT://额度计算中
                    break;
                case UserStatusType.CERTIFIED:     //已认证
                case UserStatusType.CERTIFIED_LOAD: //有借款记录
                case UserStatusType.BLOCKED_ACCOUNT: //黑名单
                    list = getCertifiedInfoList(customerStatus);
                    resultMap.put("products", list);
                    List<PayOrderInfoVO> repaymentList = payOrderInfoService.loadValidPayOrderInfoVOByUserId(user.getId());
                    if(customerStatus==UserStatusType.CERTIFIED_LOAD ) {
                        resultMap.put("repayments", repaymentList);
                    }else if(customerStatus == UserStatusType.BLOCKED_ACCOUNT){
                        if(repaymentList != null && repaymentList.size()>0){
                            resultMap.put("userStatus", UserStatusType.BLOCKED_RECORD);//黑名单有借款记录
                        }
                        resultMap.put("repayments", repaymentList);
                    }
                    break;
            }
        } else {//用户未登录，产品显示模板数据
            list = customerHomePageInfoService.getDefaultList();
            resultMap.put("products", list);
            resultMap.put("userStatus", UserStatusType.NOT_LOGIN_IN);
        }
        return success(resultMap);
    }

    /**
     * 获取首页banner图数据
     *
     * @return
     */
    private List<AdvertisementVO> getBannerList() {
        return advertisementService.findByBizType(FeatureType.HOME_BIZ_TYPE);
    }

    /**
     * 获取认证完成 相关产品信息
     *
     * @return
     */
    private List<CustomerHomePageInfoVO> getCertifiedInfoList(int type) {

        User user = this.getCurrentUser();

        List<CustomerHomePageInfoVO> list = new ArrayList<CustomerHomePageInfoVO>();

        CustomerCreditResultVO customerCreditResultVO = customerCreditResultService.loadVOByUserId(getCurrentUser().getId());

        CustomerHomePageInfoVO customerHomePageInfoVO=customerHomePageInfoService.loadVOByType(BorrowType.SINGLELOAN);

        getValidSingleLoanAmt(customerCreditResultVO,customerHomePageInfoVO);

        List<PayOrderInfoVO> auditList = payOrderInfoService.loadVoAuditByUserId(user.getId(), BorrowType.SINGLELOAN);
        if (!CollectionUtils.isEmpty(auditList)) {
            //说明用户有一笔借款正在审核中或者放款中(优先级高于可贷额度)
            customerHomePageInfoVO.setAmountContent("您有1笔借款正在处理中");

        } else {
            this.getSingleLoanAuto(customerHomePageInfoVO);
        }
        list.add(customerHomePageInfoVO);

        list.add(this.getLightLoanAuto());
        return list;
    }

    private Integer getValidSingleLoanAmt(CustomerCreditResultVO customerCreditResultVO,CustomerHomePageInfoVO customerHomePageInfoVO)
    {
        Integer sum = payOrderInfoService.loadSumByUserId(getCurrentUser().getId());
        //customerHomePageInfoVO.setValidAmount(customerCreditResultVO.getSingleAmt());
        customerHomePageInfoVO.setAmount(customerCreditResultVO.getSingleAmt());

        //Integer validAmt=customerCreditResultVO.getSingleAmt();
        Integer validAmt=-1;//用-1为了区分用户刚认证完成之后，无贷款记录的首页显示文案

        if (sum != null && sum >= 0) {//有贷款状态
            validAmt = customerCreditResultVO.getSingleAmt()-sum;
        }
        customerHomePageInfoVO.setValidAmount(validAmt);
        return validAmt;
    }

    /**
     * 获取小额贷动态文案
     *
     * @param customerHomePageInfoVO
     * @return
     */
    private void getSingleLoanAuto(CustomerHomePageInfoVO customerHomePageInfoVO) {

        String content = (String) creditConvertService.convert(CreditConverterType.SingleOrderStatusToContent, customerHomePageInfoVO, getCurrentUser().getId());

        if (SysStringUtils.isNotEmpty(content))
            customerHomePageInfoVO.setAmountContent(content);
    }

    /**
     * 获取闪电贷动态文案信息
     *
     * @return
     */
    private CustomerHomePageInfoVO getLightLoanAuto() {
        User user = this.getCurrentUser();
        CustomerHomePageInfoVO customerHomePageInfoVO = customerHomePageInfoService.loadVOByType(BorrowType.LIGHTLOAN);

        String content = (String) creditConvertService.convert(CreditConverterType.LightOrderStatusToContent, user.getId(), null);

        if (SysStringUtils.isNotEmpty(content))
            customerHomePageInfoVO.setAmountContent(content);

        return customerHomePageInfoVO;
    }
}
